package com.caipiao.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.caipiao.mapper.SBankMapper;
import com.caipiao.mapper.SUserBankMapper;
import com.caipiao.mapper.SUserMapper;
import com.caipiao.pojo.*;
import com.caipiao.service.UserBankService;
import com.caipiao.util.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by Administrator on 2019/1/2.
 */
@Service
@Transactional
public class UserBankServiceImpl implements UserBankService {

    private static final Logger LOG = LoggerFactory.getLogger(UserBankServiceImpl.class);

    //银行卡类别验证key
    private static final String BANKCARD_INFO_KEY = "fb5092b74ae53fe9e1b5c33d813f65ae";

    //银行卡四要素
    private static final String BANKCARD_4_KEY = "6734f241236a5cfad3a3d9a2b182afb7";

    //银行卡类别验证请求url
    private static final String BANKCARD_INFO_URL = "http://v.juhe.cn/bankcardinfo/query";

    //银行卡四要素请求url
    private static final String BANKCARD_4_URL = "http://v.juhe.cn/verifybankcard4/query";

    @Autowired
    private SUserMapper userMapper;
    @Autowired
    private SUserBankMapper userBankMapper;
    @Autowired
    private SBankMapper bankMapper;

    @Override
    public ObjectResult bindingBankNo(XMLBean xmlBean) {
        //绑卡
        String userId = CommonUtils.decToken(xmlBean.getToken());
        SUser resultUser =userMapper.selectByPrimaryKey(Integer.parseInt(userId));
        if (resultUser == null){
            return ObjectResult.build("0", "用户信息错误,请重试");
        }

        if (resultUser.getIsRealname() == 1){
            return ObjectResult.build("0", "您已绑定身份证");
        }

        SUserBank userBank = new SUserBank();
        userBank.setUserId(Integer.parseInt(userId));
        SUserBank sUserBank = userBankMapper.selectByMap(userBank);
        if (sUserBank != null){
            return ObjectResult.build("0", "您已绑定银行卡");
        }

        if(StringUtil.isEmpty(xmlBean.getSubBranch())){
            return ObjectResult.build("0", "支行不能为空");
        }

//        HashMap<String, String> bankCardInfoMap = new HashMap<>();
//        bankCardInfoMap.put("bankcard", xmlBean.getBankcard());
//        bankCardInfoMap.put("key", BANKCARD_INFO_KEY);
//        //验证卡类型
//        ObjectResult result = HttpClientUtil.verificationOfBankCard(BANKCARD_INFO_URL, bankCardInfoMap);
//
//        if (result.getCode().equals("1")){
//
//            Map<String,Object> resultMap = (Map<String, Object>) result.getData();
//            Map<String,Object> result_1 = (Map<String, Object>) resultMap.get("result");
//
//            if ((int)resultMap.get("error_code") != 0){
//
//                return ObjectResult.build("0", resultMap.get("reason").toString());
//
//            } else if ((int)resultMap.get("error_code") == 10012){
//                LOG.info("聚合银行卡类型及真伪查询,可请求的次数不足");
//                return ObjectResult.build("0", "身份信息审核中,请稍后重试");
//
//            }else if ((int)resultMap.get("error_code") == 10020){
//
//                return ObjectResult.build("0", "接口维护,请稍后重试");
//
//            } else if (result_1.get("bankcard").equals(xmlBean.getBankcard())){
//
//
//                if (!result_1.get("cardtype").equals("借记卡")){
//
//                    return ObjectResult.build("0", "不支持"+result_1.get("cardtype"));
//                }
//
//                //支持的银行查询,并获取机构号
//                SBank sBankType = bankMapper.selectBytitle("%"+result_1.get("bank")+"%");
//                if (sBankType == null ){
//                    return ObjectResult.build("0", "不支持此卡");
//                }

        //四要素验证
        String serialNumber = CommonUtils.getRechargeNo("V") + RandomUtil.getRandom(8);
        HashMap<String, String> bankCard4Map = new HashMap<>();
        bankCard4Map.put("key", BANKCARD_4_KEY);
        bankCard4Map.put("realname", xmlBean.getRealname());
        bankCard4Map.put("idcard", xmlBean.getIdcard());
        bankCard4Map.put("bankcard", xmlBean.getBankcard());
        bankCard4Map.put("mobile", xmlBean.getMobile());
//                bankCard4Map.put("uorderid", serialNumber);

        ObjectResult objectResult = HttpClientUtil.verificationOfBankCard(BANKCARD_4_URL, bankCard4Map);

        if (objectResult.getCode().equals("1")){

            Map<String,Object> dataMap = (Map<String, Object>) objectResult.getData();
            Map<String,Object> dataMap_1 = (Map<String, Object>) dataMap.get("result");

//            if ((int)resultMap.get("error_code") != 0){
//
//                return ObjectResult.build("0", resultMap.get("reason").toString());
//
//            } else if ((int)resultMap.get("error_code") == 10012){
//
//                LOG.info("银行卡四要素可请求的次数不足");
//                return ObjectResult.build("0", "身份信息审核中,请稍后重试");
//
//            }else if ((int)resultMap.get("error_code") == 10020){
//
//                return ObjectResult.build("0", "接口维护,请稍后重试");
//
//            }else
            if (dataMap_1.get("res").toString().equals("1")){

                if (dataMap_1.get("realname").equals(xmlBean.getRealname()) && dataMap_1.get("bankcard").equals(xmlBean.getBankcard())
                        && dataMap_1.get("idcard").equals(xmlBean.getIdcard()) && dataMap_1.get("mobile").equals(xmlBean.getMobile())){

                    try {
                        //更新数据库,用户
                        resultUser.setIsRealname(1);
                        resultUser.setRealname(xmlBean.getRealname());
                        userMapper.updateByPrimaryKeySelective(resultUser);

                        Integer user_Id = resultUser.getId();
                        //更新数据库,银行卡
                        SUserBank bank = new SUserBank();
                        bank.setUserId(user_Id);//用户id
                        bank.setCardNo(xmlBean.getBankcard());
                        bank.setMobile(xmlBean.getMobile());//卡的手机号
                        bank.setIdNo(xmlBean.getIdcard());//身份证号
                        bank.setAcctName(xmlBean.getRealname());//该卡归属人姓名
                        bank.setAddTime(new Date());//添加日期
                        bank.setSubBranch(xmlBean.getSubBranch());
                        bank.setBankId(Integer.parseInt(xmlBean.getId()));
                        bank.setModifyTime(new Date());

                        userBankMapper.insertSelective(bank);

                        return ObjectResult.build("1", "绑卡成功");
                    } catch (RuntimeException e) {
                        TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                        ExceptionUtil.logError(e,LOG);
                        return ObjectResult.build("0", "服务器异常0x06,请联系客服处理");
                    }
                }else {
                    return ObjectResult.build("0", "信息错误");
                }

            }else {
                return ObjectResult.build("0", dataMap_1.get("message").toString());
            }

        }else {
            return objectResult;
        }
//    }else {
//        return ObjectResult.build("0", "银行卡信息错误");
//    }

//        }else {
//            return result;
//        }
    }

    @Override
    public ObjectResult userBank(XMLBean xmlBean) {
        String userId = CommonUtils.decToken(xmlBean.getToken());
        SBank sBank = bankMapper.selectUserBank(Integer.parseInt(userId));
        sBank.setLogo(ConfigUtils.ADMIN_URL+sBank.getLogo());
        return ObjectResult.build("1","成功",sBank);
    }

    @Override
    public ObjectResult relieveBank(XMLBean xmlBean) {
        String userId =CommonUtils.decToken(xmlBean.getToken());

        SUser resultUser =userMapper.selectByPrimaryKey(Integer.parseInt(userId));

        if (resultUser == null){
            return ObjectResult.build("0", "用户信息错误,请重试");
        }

        SUserBank bank = new SUserBank();
        bank.setUserId(Integer.parseInt(userId));
        SUserBank sUserBank = userBankMapper.selectByMap(bank);
        if (sUserBank == null){
            return ObjectResult.build("0", "您未绑定银行卡");
        }

        //修改银行卡状态
        sUserBank.setStatus(0);
        userBankMapper.updateByPrimaryKeySelective(sUserBank);
        //修改用户绑卡状态
        resultUser.setIsRealname(0);
        userMapper.updateByPrimaryKeySelective(resultUser);


        return ObjectResult.build("1","解绑银行卡成功");
    }
}
